<template>
  <div class="drag-wrap">
    <div class="drag-box col sb" ref="drag">
      <div>↑top{{rect.top|translateNum}}</div>
      <div class="row sb ac">
        <div>←left{{rect.left|translateNum}}</div>
        <div>←right{{rect.right|translateNum}}</div>
      </div>
      <div>↑bottom{{rect.bottom|translateNum}}</div>
    </div>

    <div class="tip">
      y轴是否在可视区域(top > 视口高度 && bottom > 0): {{visibleY}}
      <br>
      x轴是否在可视区域(left &lt; 视口宽度 && right > 0): {{visibleX}}
    </div>
  </div>
</template>

<script>
export default {
  data(){
    return{
      rect:{}
    }
  },
  methods:{
    initDrag(){
      const _this = this
      let drag = this.$refs.drag
      let x = 0 // 这是点击距离屏幕最上方的位置
      let y = 0
      let ox = 0
      let oy = 0
      let able = false
      drag.addEventListener('mousedown', function(evt){
        x = evt.clientX
        y = evt.clientY
        ox = x - drag.offsetLeft
        oy = y - drag.offsetTop
        able = true
        // console.log(x, y, ox, oy)
      })
      drag.addEventListener('mousemove', function(evt){
        if(!able) return
        drag.style.left = evt.clientX - ox  + 'px'
        drag.style.top = evt.clientY - oy + 'px'
        _this.rect = drag.getBoundingClientRect()
        // console.log(this.rect)
      })
      document.addEventListener('mouseup', function(evt){
        able = false
      })
    }
  },
  filters:{
    translateNum(d){
      if(!d) return 
      return d.toFixed(2)
    }
  },
  computed:{
    visibleY(){
      return this.rect.top < window.innerHeight && this.rect.bottom > 0
    },
    visibleX(){
      // console.log(window.innerWidth)
      return this.rect.left < window.innerWidth && this.rect.right > 0
    }
  },
  mounted(){
    const _this = this
    this.initDrag()
    document.addEventListener('scroll', function(evt) {
      let drag = _this.$refs.drag
      _this.rect = drag.getBoundingClientRect()
    })
  }
}
</script>

<style lang="less" scoped>
.drag-wrap{
  width: 200vw;
  height: 200vh;
  position: relative;
  .box{
    width: 100px;
    height: 100%;
    border: 2px solid #000;
    position: absolute;
  }
  .drag-box{
    width: 200px;
    height: 200px;
    background-color: brown;
    position: absolute;
    text-align: center;
    color: #fff;
    // margin: 20px;
  }

  .tip{
    position: fixed;
    color: #333;
  }
}

.col{
  display: flex;
  flex-direction: column;
}
.row{
  display: flex;
}
.sb{
  justify-content: space-between;
}
.ac{
  align-items: center;
}
.f1{
  flex: 1;
}
</style>